package com.tac.xiangmu3.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tac.xiangmu3.common.R;
import com.tac.xiangmu3.pojo.Admin;
import com.tac.xiangmu3.service.AdminService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;
    /**
     * 登录接口
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public R login(String username,String password){
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);
        Admin admin = adminService.getOne(queryWrapper);
        if(admin!=null){
            queryWrapper.eq(Admin::getPassword,password);
                Admin one = adminService.getOne(queryWrapper);
                if(one!=null){
                    JwtBuilder builder = Jwts.builder();
                    String token = builder.setIssuedAt(new Date())
                            .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                            .setId(one.getId() + "")
                            .signWith(SignatureAlgorithm.HS256, "tac666")
                            .compact();
                    return R.success(one,token);
                }else {
                    return  R.error("密码错误");
                }
            }
            return  R.error("账户不存在");

    }
}
